<template>
    <div>
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="工作站编码">
                        <el-input placeholder="请输入内容" v-model="params.workstationCode" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="7">
                    <el-form-item label="工作站名称">
                        <el-input placeholder="请输入内容" v-model="params.workstationName" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="所在车间">
                        <el-select v-model="params.workshopCode" placeholder="请选择">
                            <el-option v-for="workshops in workshop" :key="workshops.workshopCode"
                                :label="workshops.workshopName" :value="workshops.workshopCode"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="12">
                <el-col :span="7">
                    <el-form-item label="所属工序">
                        <el-select v-model="params.processCode" placeholder="请选择">
                            <el-option v-for="processes in process" :key="processes.processCode"
                                :label="processes.processName" :value="processes.processCode"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
            </el-row>
        </el-form>

        <el-button style="background-color:#ADD8E6" @click="insert" :icon="Plus">新增</el-button>
        <el-button style=" background-color: #90EE90" plain :disabled="isSingleRowSelected" @click="UpdateID"
            :icon="Edit">修改</el-button>
        <el-button style="background-color: #FFCCCB" plain :disabled="deleteDisabled" @click="Delete1"
            :icon="Delete">删除</el-button>

        <div style="display: flex; flex-direction: column; gap: 10px;">
            <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column prop="workstationCode" label="工作站编号" width="150"></el-table-column>
                <el-table-column prop="workstationName" label="工作站名称" width="150"></el-table-column>
                <el-table-column prop="workstationLocation" label="工作站地点" width="150"></el-table-column>
                <el-table-column prop="workshop.workshopName" label="所在车间名称" width="150"></el-table-column>
                <el-table-column prop="process.processName" label="所属工序" width="150"></el-table-column>
                <el-table-column prop="status" label="是否启用" width="180" v-slot="options">
                    <el-tag :type="options.row.status == '0' ? 'success' : 'danger'">
                        {{ options.row.status == '0' ? '是' : '否' }}
                    </el-tag>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="150"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template #default="scope">
                        <el-button type="primary" link @click="Update(scope.$index, scope.row)"
                            :icon="Edit">修改</el-button>
                        <el-button type="primary" link @click="Delete2(scope.row)" :icon="Delete">删除</el-button>
                    </template>
                </el-table-column>

            </el-table>
            <!-- 分页组件 -->
            <el-row>
                <el-col :span="24">
                    <div class="demo-pagination-block">
                        <el-pagination v-model:current-page="params.currentPage" v-model:page-size="params.pageSize"
                            background :default-page-size="params.pageSize" :page-sizes="pageSizes"
                            layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResult.total)"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
            <!-- 分页组件结束 -->
        </div>



        <!-- 弹窗 -->
        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="50%" @close="handleClose">
            <el-row>
                <el-col :span="10">
                    <el-form-item label="工作站编码" label-width="100px">
                        <el-input v-model="formData.workstationCode" placeholder="请输入编码" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="工作站名称" label-width="100px">
                        <el-input v-model="formData.workstationName" placeholder="请输入名称" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="10">
                    <el-form-item label="工作站地点" label-width="100px">
                        <el-input v-model="formData.workstationLocation" placeholder="请输入地点" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="所属车间" label-width="100px">
                        <el-select v-model="formData.workshopCode" placeholder="请选择">
                            <el-option v-for="workshops in workshop" :key="workshops.workshopCode"
                                :label="workshops.workshopName" :value="workshops.workshopCode"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="10">
                    <el-form-item label="所属工序" label-width="100px">
                        <el-select v-model="formData.processCode" placeholder="请选择">
                            <el-option v-for="processes in process" :key="processes.processCode"
                                :label="processes.processName" :value="processes.processCode"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="启用状态" label-width="100px">
                        <el-radio-group v-model="formData.status">
                            <el-radio value="0">是</el-radio>
                            <el-radio value="1">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="备注">
                        <el-input v-model="formData.remark" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注"
                            clearable type="textarea"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit"> 确定</el-button>
                    <el-button type="primary" @click="close">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { findWorkstation, insertWorkstation, updateWorkstation, deleteWorkstation } from '@/apis/xms/index';
import { findWorkshop } from '@/apis/zyj/workshop'
import { findProcessSetting } from '@/apis/zyj/ProcessSettings'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Delete, Plus, Edit } from '@element-plus/icons-vue';




const pageResult = ref({}) // 表格分页数据
let salesorder = ref([]); // 表格数据
const pageSizes = [2, 5, 8, 10] // 分页大小
const workshop = ref([]) // 车间列表
const process = ref([]) // 工序列表
const visible = ref(false) // 弹窗显示状态
const title = ref('') // 弹窗标题
let ids = ref([]) // 选中行的id数组
const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
let roleVal = ref([]); //选中行
const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
const formData = ref({
    workstationId: '',
    workstationCode: '',
    workstationName: '',
    workstationLocation: '',
    workshop: '',
    workshopCode: '',
    processCode: '',
    status: '0',
    remark: ''
}) // 弹窗表单数据
const params = ref({
    currentPage: 1,
    pageSize: 5,
    workstationCode: '',
    workstationName: '',
    workshopCode: '',
    processCode: '',
    status: '',
    remark: ''
}) // 查询参数


// 参数搜索查询数据
const handleSearch = async () => {
    console.log(params.value)
    pageResult.value = await findWorkstation(params.value)
    salesorder.value = pageResult.value.records
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = (currentPage) => {
    params.value.currentPage = currentPage
    handleSearch() // 数据刷新
}
/**
 * 处理分页大小变化
 * @param size 分页大小
 */
const handleSizeChange = (size) => {
    params.value.pageSize = size
    handleSearch() // 数据刷新
}



onMounted(async () => {
    pageResult.value = await findWorkstation(params.value) // 获取分页数据
    salesorder.value = pageResult.value.records // 获取表格数据
    // 获取车间列表
    workshop.value = await findWorkshop('', '-1', '-1')
    // 获取工序列表
    process.value = await findProcessSetting('', '-1', '-1')

})

let insert = () => {
    visible.value = true;
    title.value = '新增工作站';
}

let UpdateID = () => {
    visible.value = true;
    title.value = '修改工作站';
}
let Update = (index, row) => {
    console.log(row);
    visible.value = true;
    title.value = '修改工作站';
    // formData.value = {
    //     workstationId: row.workstationId,
    //     workstationCode: row.workstationCode,
    //     workstationName: row.workstationName,
    //     workstationLocation: row.workstationLocation,
    //     workshopCode: row.workshop.workshopCode,  // 确保路径正确  
    //     processCode: row.process.processCode,      // 确保路径正确  
    //     status: row.status,
    //     remark: row.remark
    // };

    formData.value = { ...row }

}



/**
 * 提交表单
 */
const onSubmit = async () => {
    if (title.value == '新增工作站') {
        await insertWorkstation(formData.value)
    } else if (title.value == '修改工作站') {
        console.log("xx", formData.value)
        await updateWorkstation(formData.value).then((res) => {
            if (res == "成功") {
                ElMessage.success(`${title.value}成功`)
            } else {
                ElMessage.error("修改失败")
            }
        })
    }
    visible.value = false;
    handleSearch();

}

const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.workstationId) // 使用map方法过滤出选中行的logId数组

    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        formData.value = { ...val[0] };//把选中的这条数据添加给修改数据（）
    }

}





//批量删除
const Delete1 = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteWorkstation(ids.value);  // 将单个ID传递给 deleteCustomer 
        console.log(`删除的ID:`, ids.value);
        pageResult.value = await findWorkstation(params.value);
        salesorder.value = pageResult.value.records;
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

const Delete2 = async (row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${row.workstationId}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteWorkstation([row.workstationId]);  // 将单个ID传递给 deletesspplier 方法

        console.log(`删除的ID:`, row.workstationId);

        // 从表格数据中移除当前行
        salesorder.value = salesorder.value.filter(item => item.workstationId !== row.workstationId);

        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

/**
 * 关闭弹窗,处理数据
 */
const handleClose = () => {
    if (title.value == "新增工作站") {
        resetData()
    }
}
/**
 * 重置数据
 */
function resetData() {
    formData.value = {}
    title.value = ''
}



let close = () => {
    visible.value = false;
    loadData();
};

/**
 * 加载数据
 */
const loadData = async () => {
    await handleSearch();
};

/**
 * 重置搜索参数
 */
const paramsReset = () => {
    params.value = {
        materialName: '',
        status: null
    }
    handleSearch();

}
</script>

<style scoped>
.demo-pagination-block {
    display: flex;
    /* 使其成为 flexbox 容器 */
    justify-content: flex-end;
    /* 将内容对齐到右侧 */
    margin-top: 20px;
}
</style>
